package cn.seaboot.admin.image;


import com.luciad.imageio.webp.WebPReadParam;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.FileImageInputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @author Mr.css
 * @version 2022-07-06 9:24
 */
public class ImageUtils {

    public static void main(String[] args) throws IOException {
        File in = new File("C:\\Users\\ASUS\\Desktop\\test.webp");
        String filename = in.getName().replace(".webp", ".png");
        File out = new File(in.getParent(), filename);
        webpToPng(in, out);
    }

    /**
     * webp convert to png
     *
     * @param in  输入文件
     * @param out 输出文件
     */
    public static void webpToPng(File in, File out) throws IOException {
        //  Obtain a WebP ImageReader instance
        ImageReader reader = ImageIO.getImageReadersByMIMEType("image/webp").next();

        //  Configure decoding parameters
        WebPReadParam webPReadParam = new WebPReadParam();
        webPReadParam.setBypassFiltering(true);

        //  Configure the input on the ImageReader
        reader.setInput(new FileImageInputStream(in));

        //  Decode the image
        BufferedImage image = reader.read(0, webPReadParam);

        //  the `png` can use `jpg`
        ImageIO.write(image, "png", out);
    }
}
